#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define PATH "."
#define FILENAME "fifo"

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

// 创建管道
class NamedFifo
{
public:
    NamedFifo(const std::string path, const std::string name)
        : _path(path), _name(name)
    {
        _fifoname = _path + "/" + _name;
        umask(0);
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            ERR_EXIT("mkfifo");
        }
        std::cout << "mkfifo success" << std::endl;
    }
    ~NamedFifo()
    {
        int n = unlink(_fifoname.c_str());
        if (n < 0)
        {
            ERR_EXIT("unlink");
        }
        std::cout << "unlink success" << std::endl;
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

// 打开文件
class FileOper
{
public:
    FileOper(const std::string& path, const std::string& name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open");
        }
        std::cout << "open fifo success" << std::endl;
    }

    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open");
        }
        std::cout << "open fifo sucess" << std::endl;
    }

    void Write()
    {
        std::string message;
        int cnt = 0;
        pid_t id = getpid();
        while (true)
        {
            std::cout << "请输入：" << std::endl;
            std::getline(std::cin, message);
            message += (", message number: " + std::to_string(cnt++) + ", [" + std::to_string(id) + "]");
            write(_fd, message.c_str(), message.size());
        }
    }

    void Read()
    {
        while (true)
        {
            char buf[1024];
            int num = read(_fd, buf, sizeof(buf) - 1);
            if (num > 0)
            {
                buf[num] = 0;
                std::cout << "client say# " << buf << std::endl;
            }
            else if (num == 0)
            {
                std::cout << "Client quit! me too!" << std::endl;
                break;
            }
            else
            {
                std::cout << "read error" << std::endl;
                break;
            }
        }
    }

    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }

    ~FileOper()
    {
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};